package com.auto.survey.activity.test

import android.text.TextUtils
import com.auto.survey.base.CustomApplication
import com.auto.survey.log.AppLogger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

// 命令执行器
class CommandExecutor {
    private val scope = CoroutineScope(Dispatchers.IO) // 使用 IO 调度器执行命令

    private var resultExecutorCallback: ((List<String>) -> Unit)? = null

    private var conditionChecker: ((previousResult: String) -> Boolean)? = null //第一层过滤，判断通信返回结果是否正常

    private var conditionParse:((parseResult:String)-> String)?=null   //第二层过滤，对返回的结果进一步处理成需要的格式

    // 串行执行命令列表
    suspend fun executeCommandsSequentially(commands: List<ICommanExecutor>): List<String> {
        val results = mutableListOf<String>()

        for (index in commands.indices) {
            // 第一个命令直接执行，后续命令检查前置条件
//            if (index > 0) {
//                val previousResult = results.lastOrNull() ?: ""
//                if (!conditionChecker?.invoke(previousResult)!!) {
//                    println("条件不满足，终止命令执行")
//                    AppLogger.getInstance(CustomApplication.getContext()).i("CommandExecutor", "条件不满足，终止命令执行")
//                    break
//                }
//            }

            val command = commands[index]
            val result = command.execute()
            if (conditionChecker != null && conditionChecker?.invoke(result) == false) {
                println("条件不满足，终止命令执行")
                AppLogger.getInstance(CustomApplication.getContext()).i("CommandExecutor", "条件不满足，终止命令执行")
                break
            }

            var strJsonResult:String? = null
            if (conditionParse != null) {
                strJsonResult = conditionParse?.invoke(result)
            }

            if (!TextUtils.isEmpty(strJsonResult)) {
                results.add(result)
            }
        }

        return results
    }

    // 启动执行（非挂起函数，用于外部调用）
    fun startExecution(commands: List<ICommanExecutor>) {
        scope.launch {
            try {
                val results = executeCommandsSequentially(commands)
                resultExecutorCallback?.invoke(results)
                println("所有命令执行完成: $results")
            } catch (e: Exception) {
                println("命令执行出错: ${e.message}")
            }
        }
    }


    // 设置条件检查器
    fun setConditionChecker(checker: (previousResult: String) -> Boolean): CommandExecutor {
        this.conditionChecker = checker
        return this
    }

    fun setResultExecutorCallback(callback: (List<String>) -> Unit): CommandExecutor {
        this.resultExecutorCallback = callback
        return this
    }

    fun setConditionParse(parse:(parseResult:String) -> String) : CommandExecutor {
        this.conditionParse = parse
        return this
    }

    // 关闭执行器
    fun shutdown() {
        scope.cancel()
    }
}